from flask import jsonify, request
from app.users.model import Users

from app.auth.auths import Auth
from app import _common
import logging

def init_api(app):
	
	@app.route('/register', methods=['POST'])
	def register():
		email = request.form.get('email')
		username = request.form.get('username')
		password = request.form.get('password')
		user = Users( email=email, username=username, password=password)
		user.id = 1
		result = user.add()
		if user.id:
			returnUser = {
				'id': user.id,
				'username': username,
				'email': user.email,
				'login_time': user.login_time
			}
			return jsonify(_common.trueReturn(returnUser, "注册成功"))
		else:
			return jsonify(_common.falseReturn('', "注册失败"))
	
	@app.route('/login', methods=['POST'])
	def login():
		username = request.form.get('username')
		password = request.form.get('password')
		
		if (not username or not password):
			return jsonify(_common.falseReturn('', '用户名和密码不能为空'))
		else:
			return Auth.authenticate(username, password)
		
	@app.route('/user', methods=['POST'])
	def get():
		auth_header = request.headers.get('Authorization')	#: 验证 header是否是 Authorization[即 key]
		logging.info('auth_header: ' + auth_header)
		
		result = Auth.identify(auth_header)
		if (result['status'] and result['data']):
			user = Users.get_by_id(result['data'])	#result['data'] 是 userId
			returnUser = {
				'id': user.id,
				'username': user.username,
				'email': user.email,
				'login_time': user.login_time
			}
			result = _common.trueReturn(returnUser, "请求成功")
		return jsonify(result)